package controllers

import (
	"fmt"
	"github.com/dchest/captcha"
	"github.com/gin-gonic/gin"
	"log"
	"micro-bbs/datamodels"
	"micro-bbs/initialize"
	"micro-bbs/libs"
	"micro-bbs/services"
	"net/http"
	"strconv"
)

type PostController struct {
	PostService services.PostInterfaceService
}

//获取帖子列表页
func (this *PostController) List(c *gin.Context){
	cate := c.Param("cate")
	page := c.DefaultQuery("page", "1")
	statusString := c.DefaultQuery("status", "0")
	status, _ := strconv.Atoi(statusString)
	fmt.Println("cate",cate)
	fmt.Println("page",page)
	category := map[string]int{
		"all":     0,  //全部
		"quiz":    1,  //提问
		"share":   2,  //分享
		"discuss": 3,  //讨论
		"suggest": 4,  //建议
		"notice":  5,  //公告
		"news":    6,  //动态
	}
	var params datamodels.PostPageListQuery
	params.Page,_ = strconv.ParseInt(page, 10, 64)
	params.PerPage = 20
	var cli int
	if cate != "all" {
		changeCate := category[cate]
		params.CategoryId = &changeCate
		cli = category[cate]
	}
	if status > 0 {
		switch status {
			case 1:
				val := 0
				params.Solved = &val
			case 2:
				val := 1
				params.Solved = &val
			case 3:
				val := 1
				params.IsWonderful = &val
		}
	}
	postList, _ := this.PostService.GetPostPageList(params)
	initialize.IrisLog.Infof("[主页控制器-HomeIndex-获取postList数据]-[%s]", libs.StructToJson(postList))
	total := postList.(map[string]interface{})["total"] //map断言后再从map取值
	fmt.Println("total is:",total)
	pages := libs.CreatePaging(params.Page, params.PerPage, int64(total.(int)))
	fmt.Println("pages is:",pages)
	c.JSON(http.StatusOK, libs.ReturnJson(200,"", gin.H{
		"title": "综合栏目-雷小天社区",
		"data": postList,
		"paging": pages,
		"cli": cli,
		"category": cate,
		"status": status,
		"prev": pages.Page - 1,
		"next": pages.Page + 1,
	}))
}

//获取帖子详情页
func (this *PostController) Detail(c *gin.Context){
	idStr := c.Param("id")
	id, _ := strconv.Atoi(idStr)
	initialize.IrisLog.Infof("[帖子控制器-PostDetail-http请求数据]-[%d]", id)

	result, err := this.PostService.GetPost(int64(id))
	initialize.IrisLog.Infof("[帖子控制器-PostDetail-post返回数据]-[%s]", libs.StructToJson(result))
	if err != nil {
		c.JSON(http.StatusNotFound, libs.ReturnJson(500,"帖子未找到", ""))
		return
	}
	//获取评论
	var query datamodels.ParamsPostCommentList
	query.PostId = id
	commentList, _ := this.PostService.GetPostCommentList(query)
	initialize.IrisLog.Infof("[帖子控制器-commentList返回数据]-[%s]", libs.StructToJson(commentList))
	c.JSON(http.StatusOK, libs.ReturnJson(200,"", gin.H{
		"title": result.(datamodels.BbsPostInfoVo).Title,
		"address": "bbs.100txy.com",
		"id": id,
		"data": result,
		"comment": commentList,
	}))
}

//用户添加帖子
func (this *PostController) AddPost(c *gin.Context){
	//绑定参数
	type Query struct {
		Title       string  `json:"title" binding:"required"`       //标题
		Type        int     `json:"type" binding:"required"`        //类型
		Content     string  `json:"content" binding:"required"`     //内容
		Code        string  `json:"code" binding:"required"`      	//验证码
		CaptchaId   string  `json:"captcha_id" binding:"required"`  //验证码ID
		Reward      int     `json:"reward" binding:"required"`      //飞吻
	}
	var query Query

	if err := c.ShouldBind(&query); err != nil {
		log.Println("Controller:PostController", "发布帖子检测参数",err.Error())
		c.JSON(http.StatusOK, libs.ReturnJson(4000, "", nil))
		return
	}
	//检查验证码
	verifyVal := captcha.VerifyString(query.CaptchaId, query.Code)
	if !verifyVal {
		c.JSON(http.StatusOK, libs.ReturnJson(4005,"", gin.H{}))
		return
	}
	//从解析token中间件获取用户ID
	uid, ok := c.Get("jwtUserId")  //取值 实现了跨中间件取值
	if !ok{
		c.JSON(http.StatusOK, libs.ReturnJson(5002,"", gin.H{}))
	}
	//根据uid获取用户信息
	user,err := services.NewUserService().GetUserInfoById(uid.(int64))
	fmt.Println("user:",user)
	if err != nil || user == nil {
		fmt.Println("rpc request failed:", err)
		return
	}
	//效验奖励
	if  int(user.(map[string]interface{})["reward"].(float64)) < query.Reward {
		c.JSON(http.StatusOK, libs.ReturnJson(5003,"", gin.H{}))
		return
	}
	//{{rpc更新用户奖励
	var protoUser datamodels.ProtoUser
	protoUser.Id = uid.(int64)
	//protoUser.Reward = int64(user.(map[string]interface{})["reward"].(float64)) - int64(query.Reward)//取0不删减
	protoUser.Reward = 0
	//组装请求数据
	var protoUserReq datamodels.ProtoUserReq
	protoUserReq.User = protoUser
	protoUserReq.Number = int64(query.Reward)
	//点一次标记扣减操作
	recordId,err := services.NewUserService().UpdateUser(protoUserReq)
	//recordId64, err := strconv.ParseInt(recordId.(string), 10, 64)
	if recordId == 0 || err != nil{
		c.JSON(http.StatusOK, libs.ReturnJson(5105,"", gin.H{}))
		return
	}
	//}}
	//保存帖子
	var postInfo datamodels.BbsPost
	postInfo.Title = query.Title
	postInfo.Author = int(uid.(int64))
	postInfo.Content = query.Content
	postInfo.Reward = query.Reward
	postInfo.CategoryId = query.Type
	postInfo.Remark = strconv.FormatInt(recordId,10)
	result, err := this.PostService.SavePost(postInfo)
	if err != nil {
		c.JSON(http.StatusOK, libs.ReturnJson(5104,"", gin.H{}))
		return
	}

	c.JSON(http.StatusOK, libs.ReturnJson(200,"", gin.H{
		"res": true,
		"id": result,
	}))
	//二段式确认，推送mq修改消费日志状态和真实扣减飞吻奖励
	//推送发帖确认MQ
	services.NewRabbitmqService().PushConfirmPost(recordId)
	return
}